package com.yuqing.sentimentapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linkface.baselibrary.utils.AppManager;
import com.linkface.baselibrary.utils.LogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.home.fragment.HomeFragment;
import com.yuqing.sentimentapp.interfaces.ScheduleListener;
import com.yuqing.sentimentapp.mine.MineFragment;
import com.yuqing.sentimentapp.utils.InstallUtil;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.utils.UpdateAppManager;
import com.yuqing.sentimentapp.widget.jzvideo.Jzvd;
import com.yuqing.sentimentapp.workspace.WorkspaceFragment;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    @BindView(R.id.container_fragment)
    FrameLayout mContainerFragment;
    @BindView(R.id.iv_nav_home_ic)
    ImageView mIvNavHomeIc;
    @BindView(R.id.tv_nav_home_txt)
    TextView mTvNavHomeTxt;
    @BindView(R.id.ll_nav_home)
    LinearLayout mLlNavHome;
    @BindView(R.id.iv_nav_workspace_ic)
    ImageView mIvNavWorkspaceIc;
    @BindView(R.id.tv_nav_workspace_txt)
    TextView mTvNavWorkspaceTxt;
    @BindView(R.id.ll_nav_workspace)
    LinearLayout mLlNavWorkspace;
    @BindView(R.id.iv_nav_mine_ic)
    ImageView mIvNavMineIc;
    @BindView(R.id.tv_nav_mine_txt)
    TextView mTvNavMineTxt;
    @BindView(R.id.ll_nav_mine)
    LinearLayout mLlNavMine;
    private FragmentManager fragmentManager;
    private HomeFragment mHomeFragment;
    private WorkspaceFragment mWorkspaceFragment;
    private MineFragment mMineFragment;
    private long firstTime;
    private String taskFilePath;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        fragmentManager = getSupportFragmentManager();

        //设置默认tab页
        setChoiceTop(0);
        requestPermission();

        checkUpdate();
    }

    @SuppressLint("CheckResult")
    private void requestPermission() {
        //同时请求多个权限
        RxPermissions rxPermission = new RxPermissions(MainActivity.this);
        rxPermission.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_PHONE_STATE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        LogUtil.d(permission.name + " is granted.");
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        LogUtil.d(permission.name + " is denied. More info should be provided.");
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        LogUtil.d(permission.name + " is denied.");
                    }
                });

    }

    private void checkUpdate() {//检查更新
        UpdateAppManager.getUpdateAppManager().init();
        UpdateAppManager.getUpdateAppManager().onlineCheckAppUpdate(new ScheduleListener() {
            @Override
            public void progress(int progress) {

            }

            @Override
            public void start() {
            }

            @Override
            public void end(boolean success) {
                if (UpdateAppManager.isUpdate()) {
                    if (!UpdateAppManager.isDownLoad()) {
                        Activity activity = AppManager.getAppManager().currentActivity();
                        if (activity instanceof MainActivity && !activity.isFinishing()) {
                            UpdateAppManager.getUpdateAppManager().showDialog(MainActivity.this,
                                    true);
                        }
                    } else {
                        ToastUtil.showShort(getResources().getString(R.string.isDownLoad));
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 10001) {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable()) {
                taskFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            }
            File file = new File(taskFilePath + File.separator + UpdateAppManager.NAME);
            if (!file.exists()) return;
            new InstallUtil(MainActivity.this, file.getAbsolutePath()).install();
        }
    }

    private void setChoiceTop(int index) {
        //释放视频
        Jzvd.resetAllVideos();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //设置默认的tab
        clearChoiceTab();
        //隐藏页面
        hideFragment(transaction);
        switch (index) {
            case 0://首页
                //更改tab的图标
                mIvNavHomeIc.setImageResource(R.drawable.ic_nav_home_selected);
                //更改tab文字的颜色
                mTvNavHomeTxt.setTextColor(getResources().getColor(R.color.color_blue_light));
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                    transaction.add(R.id.container_fragment, mHomeFragment);
                } else {
                    transaction.show(mHomeFragment);
                }
                break;
            case 1:
                //更改tab的图标
                mIvNavWorkspaceIc.setImageResource(R.drawable.ic_nav_workspace_selected);
                //更改tab文字的颜色
                mTvNavWorkspaceTxt.setTextColor(getResources().getColor(R.color.color_blue_light));
                if (mWorkspaceFragment == null) {
                    mWorkspaceFragment = new WorkspaceFragment();
                    transaction.add(R.id.container_fragment, mWorkspaceFragment);
                } else {
                    transaction.show(mWorkspaceFragment);
                }
                break;
//            case 2:
//                //更改tab的图标
//                mIvNavStatisticsIc.setImageResource(R.drawable.ic_nav_statistics_selected);
//                //更改tab文字的颜色
//                mTvNavStatisticsTxt.setTextColor(getResources().getColor(R.color.color_blue_light));
//                if (mStatisticsFragment == null) {
//                    mStatisticsFragment = StatisticsFragment.start(BuildConfig.Base_URL + "/finebi/count", getResources().getString(R.string.statistics_yuqing_title),true, false);
//                    transaction.add(R.id.container_fragment, mStatisticsFragment);
//                } else {
//                    transaction.show(mStatisticsFragment);
//                }
//                break;
            case 2:
                //更改tab的图标
                mIvNavMineIc.setImageResource(R.drawable.ic_nav_mine_selected);
                //更改tab文字的颜色
                mTvNavMineTxt.setTextColor(getResources().getColor(R.color.color_blue_light));
                if (mMineFragment == null) {
                    mMineFragment = new MineFragment();
                    transaction.add(R.id.container_fragment, mMineFragment);
                } else {
                    transaction.show(mMineFragment);
                }
                break;
            default:
                break;
        }
        transaction.commitNowAllowingStateLoss();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (mHomeFragment != null) {
            transaction.hide(mHomeFragment);
        }
        if (mWorkspaceFragment != null) {
            transaction.hide(mWorkspaceFragment);
        }
        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }
    }

    private void clearChoiceTab() {
        mIvNavHomeIc.setImageResource(R.drawable.ic_nav_home);
        mTvNavHomeTxt.setTextColor(getResources().getColor(R.color.text_nav));

        mIvNavWorkspaceIc.setImageResource(R.drawable.ic_nav_workspace);
        mTvNavWorkspaceTxt.setTextColor(getResources().getColor(R.color.text_nav));

        mIvNavMineIc.setImageResource(R.drawable.ic_nav_mine);
        mTvNavMineTxt.setTextColor(getResources().getColor(R.color.text_nav));
    }

    @OnClick({R.id.ll_nav_home, R.id.ll_nav_workspace, R.id.ll_nav_mine})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.ll_nav_home://首页
                setChoiceTop(0);
                break;
            case R.id.ll_nav_workspace://工作台
                setChoiceTop(1);
                break;
            case R.id.ll_nav_mine://我的
                setChoiceTop(2);
                break;
        }
    }

    /**
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                ToastUtil.showShort("再按一次退出程序");
                firstTime = secondTime;
                return true;
            } else{
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
